﻿using M_Manufacture.API.Application.Command.ProductionPlanCommand;
using M_Manufacture.Domain;
using M_Manufacture.Domain.DTO;
using M_Manufacture.Repository.Interface;
using MediatR;

namespace M_Manufacture.API.Application.CommandHandlers.ProductionPlanCommandHandler
{
    public class ShowProductionPlanCommandHandler : IRequestHandler<ShowProductionPlanCommand, PageDto<ProductionPlan>>
    {
        /// <summary>
        /// 生产计划仓储接口
        /// </summary>
        protected readonly IProductionPlanRepository productionPlanRepository;

        public ShowProductionPlanCommandHandler(IProductionPlanRepository productionPlanRepository)
        {
            this.productionPlanRepository = productionPlanRepository;
        }

        public async Task<PageDto<ProductionPlan>> Handle(ShowProductionPlanCommand request, CancellationToken cancellationToken)
        {
            var res = await productionPlanRepository.GetAsync(o => o.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.ProductionPlanNumber))
            {
                res = res.Where(o => o.ProductionPlanNumber.Contains(request.ProductionPlanNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductionStatus))
            {
                res = res.Where(o => o.ProductionStatus.Contains(request.ProductionStatus)).ToList();
            }
            if (request.Pagesize == null)
            {
                request.Pagesize = res.Count();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            PageDto<ProductionPlan> page = new PageDto<ProductionPlan>();
            var size = request.Pagesize;
            var index = request.Pageindex;
            page.TotalCount = res.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)size);
            page.list = res.OrderByDescending(o => o.ProductionPlanId).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return page;
        }
    }
}
